package com.esc.print.flutter_pda_print

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Base64
import android.util.Log
import android.widget.Toast
import androidx.annotation.NonNull
import com.example.print_sdk.PrintUtil
import com.example.print_sdk.enums.ALIGN_MODE
import com.example.print_sdk.interfaces.OnPrintEventListener
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result

/** FlutterPdaPrintPlugin */
class FlutterPdaPrintPlugin : FlutterPlugin, MethodCallHandler {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private lateinit var channel: MethodChannel

    private val TAG = "FlutterPdaPrintPlugin"

    fun getLoadProgressDialog(context: Context?): LoadProgressDialog? {
        loadProgressDialog = LoadProgressDialog(context, "打印中……")
        return loadProgressDialog
    }

    companion object {
        var loadProgressDialog: LoadProgressDialog? = null
        var printUtil: PrintUtil? = null
        var mContext: Context? = null
        fun initPrintUtil(context: Context) {
            mContext = context
            printUtil = PrintUtil.getInstance()
            printUtil?.printEnableCertificate(true)
            printUtil?.printEnableMark(false)
            printUtil?.printAutoEnableMark(false)
            printUtil?.printLanguage(15)
            printUtil?.printEncode(3)
            printUtil?.setPrintDefLineSpacing()

            printUtil?.setPrintEventListener(object : OnPrintEventListener {
                override fun onPrintStatus(state: Int) {
                    Log.e("TAG", "onPrintStatus: $state")
                    when (state) {
                        0 -> {
                            if (loadProgressDialog != null) {
                                if (loadProgressDialog?.isShowing() == true) {
                                    loadProgressDialog?.cancel()
                                }
                            }
                            Toast.makeText(mContext, "打印完成", Toast.LENGTH_SHORT).show()
                        }
                        1, 3 -> Toast.makeText(mContext, "缺纸", Toast.LENGTH_SHORT).show()
                        2 -> Toast.makeText(mContext, "打印失败", Toast.LENGTH_SHORT).show()
                    }
                }

                override fun onVersion(version: String) {}
                override fun onTemperature(str: String) {}
            })
        }
    }

    /**
     * 图片
     * @param barContent
     */
    fun printImage(barContent: String?) {
        try {
            printUtil?.printStartNumber(123456)
            printUtil?.printState()
            printUtil?.printAlignment(ALIGN_MODE.ALIGN_CENTER)
            printUtil?.printLine()
            printUtil?.printImage(barContent?.let { stringtoBitmap(it) })
            printUtil?.printLine()
            printUtil?.printLine(3)
            printUtil?.printEndNumber()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 打印QR码
     * @param barContent
     */
    fun printQR(barContent: String?) {
        try {
            printUtil?.printStartNumber(123456)
            printUtil?.printState()
            printUtil?.printAlignment(ALIGN_MODE.ALIGN_CENTER)
            printUtil?.printLine()
            printUtil?.printBitmap2(barContent?.let { stringtoBitmap(it) })
            printUtil?.printLine()
            printUtil?.printLine(3)
            printUtil?.printEndNumber()
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
    　　* 将base64转换成bitmap图片
    　　*
    　　* @param string base64字符串
    　　* @return bitmap
    　　*/
    fun stringtoBitmap(string:String): Bitmap? {
        // 将字符串转换成Bitmap类型
        var bitmap:Bitmap? = null
        try {
            Log.e(TAG, "stringtoBitmap: $string")
            var bitmapArray:ByteArray
            bitmapArray = Base64.decode(string, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,
                    bitmapArray.size);
        } catch (e:Exception) {
            e.printStackTrace();
        }
        return bitmap;
    }

    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        channel = MethodChannel(flutterPluginBinding.binaryMessenger, "flutter_pda_print")
        channel.setMethodCallHandler(this)
    }

    override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
        when (call.method) {
            "getPlatformVersion" -> result.success("Android ${android.os.Build.VERSION.RELEASE}")
            "print" -> {
                try {
                    printUtil?.printStartNumber(123456)
                    printUtil?.printState()
                    printUtil?.printAlignment(ALIGN_MODE.ALIGN_CENTER)
                    printUtil?.printLine()
                    printUtil?.printText(call.argument<String>("content"))
                    printUtil?.printLine()
                    printUtil?.printLine(3)
                    printUtil?.printEndNumber()
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            "printQR"->{
                printQR(call.argument<String>("content"))
            }
            "printQR"->{
                printQR(call.argument<String>("content"))
            }
            "printImage"->{
                printImage(call.argument<String>("content"))
            }
            else -> result.notImplemented()
        }
        /* if (call.method == "getPlatformVersion") {
           result.success("Android ${android.os.Build.VERSION.RELEASE}")
         } else {
           result.notImplemented()
         }*/
    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
        channel.setMethodCallHandler(null)
    }
}
